package com.apkcore.core.ui.recyclerview

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView

/**
 * https://blog.csdn.net/lujianfeiccie2009/article/details/126210531
 */
class GridItemDecoration(
    /**
     * gridLayoutManager来获取列数
     */
    private val gridLayoutManager: GridLayoutManager,
    /**
     * 间距
     */
    private val columnSpace: Int,
    /**
     * 行距，没有设置就相同于间距
     */
    private val rowSpace: Int? = null,

    /**
     * 间距包含左右两侧
     */
    private val includeEdgeLR: Boolean = true,
    /**
     * 间距上下边，如果没有设置，那么就使用includeEdgeLR
     */
    private val includeEdgeTB: Boolean? = includeEdgeLR
) : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val spanCount = gridLayoutManager.spanCount
        val position = parent.getChildAdapterPosition(view) // 获取view 在adapter中的位置。
        val column = position % spanCount // view 所在的列

        if (includeEdgeTB ?: includeEdgeLR) {
            if (position < spanCount) { // top edge
                outRect.top = rowSpace ?: columnSpace
            }
            outRect.bottom = rowSpace ?: columnSpace // item bottom
        } else {
            // 如果position > 行数，说明不是在第一行，则不指定行高，其他行的上间距为 top=rowSpace
            if (position >= spanCount) {
                outRect.top = rowSpace ?: columnSpace // item top
            }
        }
        if (includeEdgeLR) {
            outRect.left =
                columnSpace - column * columnSpace / spanCount // spacing - column * ((1f / spanCount) * spacing)
            outRect.right =
                (column + 1) * columnSpace / spanCount // (column + 1) * ((1f / spanCount) * spacing)

        } else {
            outRect.left =
                column * columnSpace / spanCount //column * (列间距 * (1f / 列数))
            outRect.right =
                columnSpace - (column + 1) * columnSpace / spanCount // 列间距 - (column + 1) * (列间距 * (1f /列数))
        }
    }
}
